<template>
  <el-form :inline="inline" :model="formInline"  size="mini"
           label-width="125px" :rules="rules" ref="ruleForm" class="demo-form-inline">

    <template v-for="(group,groupIndex) in listcolumns" >
      <el-row>
        <div class="title" v-if="group.group_name != ''" >
          <span>{{group.group_name}}</span>
        </div>
      </el-row>



      <template v-for="(field,fieldIndex) in group.columns">
        <el-form-item v-if="field.is_input == '0'" :label="field.show_name+''" :prop="field.col_name"
                      :class="field.show_name.length>8?'changeLHight':''">

          <!--输入框-->
          <el-input v-if="field.col_style == 0" @keyup.enter.native="huiche(field)" :name="field.id"
                    @input="changeFormSubmit(field.col_name)" :disabled="field.is_disabled"
                    v-model="formInline[field.col_name]" :placeholder="field.msg"
                    :style="'width:'+field.input_width" ></el-input>

          <!--日期框-->
          <el-date-picker v-if="field.col_style == 1" :disabled="field.is_disabled"
                          value-format="yyyy-MM-dd" @input="changeFormSubmit(field.col_name)" :name="field.id"
                          v-model="formInline[field.col_name]" :placeholder="field.msg"
                          :style="'width:'+field.input_width" type="date">
          </el-date-picker>


          <!--复选框-->
          <template v-if="field.col_style == '19'">
            <el-checkbox-group v-model="formInline[field.col_name]"
                               @change="changeFormSubmit(field.col_name)">
              <el-checkbox v-for="option in field.options"
                           :label="option.key">{{option.value}}</el-checkbox>
            </el-checkbox-group>
          </template>

          <!--单选框-->
          <template v-if="field.col_style == '21'">
            <el-radio v-model="formInline[field.col_name]"
                      @change="changeFormSubmit(field.col_name)" v-for="option in field.options"
                      :label="option.key">{{option.value}}</el-radio>
          </template>

          <!--日期框年月-->
          <template v-if="field.col_style == 15">
            <el-date-picker value-format="yyyyMM" :style="'width:'+field.input_width"
                            :disabled="field.is_disabled" :name="field.id"
                            v-model="formInline[field.col_name]" :placeholder="field.msg"
                            type="month">
            </el-date-picker>
          </template>

          <!--时分秒日期框-->
          <el-date-picker v-if="field.col_style == 5" :disabled="field.is_disabled"
                          value-format="yyyy-MM-dd HH:mm:ss" @input="changeFormSubmit(field.col_name)"
                          :name="field.id" v-model="formInline[field.col_name]"
                          :placeholder="field.msg" :style="'width:'+field.input_width" type="datetime">
          </el-date-picker>

          <!--下拉框-->
          <el-select :disabled="field.is_disabled" @input="changeFormSubmit(field.col_name)"
                     v-if="field.col_style == 6 || field.col_style == 8" filterable
                     :style="'width:'+field.input_width" v-model="formInline[field.col_name]"
                     :placeholder="field.msg">
            <el-option value="" v-if="field.is_null == 0"></el-option>
            <el-option v-for="option in field.options" :label="option.value"
                       :value="option.key"></el-option>
          </el-select>

          <!--远程搜索下拉框-->
          <el-select :disabled="field.is_disabled"
                     :remote-method="(query) => remoteMethod(query,fieldIndex,item.list)" remote
                     @change="changeFormSubmit(field.col_name)" v-if="field.col_style == 16" filterable
                     :style="'width:'+field.input_width" v-model="formInline[field.col_name]"
                     :placeholder="field.msg">
            <el-option value=""></el-option>
            <el-option v-for="option in field.options" :label="option.value"
                       :value="option.key"></el-option>
          </el-select>

          <!--下拉框多选-->
          <el-select :disabled="field.is_disabled" multiple @focus="changeFormSubmit(field.col_name)"
                     v-if="field.col_style == 12 || field.col_style == 13" filterable
                     :style="'width:'+field.input_width" v-model="formInline[field.col_name]"
                     :placeholder="field.msg">
            <!--<el-option value=""></el-option>-->
            <el-option v-for="option in field.options" :label="option.value"
                       :value="option.key"></el-option>
          </el-select>


          <!--远程搜索下拉框多选-->
          <el-select :disabled="field.is_disabled" multiple
                     :remote-method="(query) => remoteMethod(query,fieldIndex,item.list)" remote
                     @change="changeFormSubmit(field.col_name)" v-if="field.col_style == 17" filterable
                     :style="'width:'+field.input_width" v-model="formInline[field.col_name]"
                     :placeholder="field.msg">
            <!--<el-option value=""></el-option>-->
            <el-option v-for="option in field.options" :label="option.value"
                       :value="option.key"></el-option>
          </el-select>

          <!-- 编辑器 DOM -->
          <div v-if="field.col_style == 3" :style="'height:300px;width:'+field.input_width">
            <div :id="'toolbar-container-'+field.id" :style="'width:'+field.input_width"></div>
            <div :id="'editor-container-'+field.id" :style="'height:300px;width:'+field.input_width">
            </div>
          </div>

          <template v-if="field.col_style == 22">
            <el-upload class="upload-demo" drag
                       :action="wwwurl+'/admin/api/UploadController/elementUiUploadDopostFileUpload'"
                       :data="{field:field.col_name,groupid:''}" :headers="headers"
                       :on-success="uploadSuccess"
                       :on-remove="(file, fileList) => {handleRemove(file, fileList, field.col_name,field.group_id)}"
                       multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </template>


          <template v-if="field.col_style == 4">
            <el-upload :action="wwwurl+'/admin/api/UploadController/elementUiUploadDopostFileUpload'"
                       list-type="picture-card" :on-preview="handlePictureCardPreview" multiple
                       :data="{field:field.col_name,groupid:''}" :headers="headers"
                       :file-list="uploadListShow[field.col_name]" :on-success="uploadSuccess"
                       :on-remove="(file, fileList) => {handleRemove(file, fileList, field.col_name,field.group_id)}">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </template>

          <el-input type="textarea" v-if="field.col_style == 7" :style="'width:'+field.input_width"
                    :disabled="field.is_disabled" @input="changeFormSubmit(field.col_name)"
                    @keyup.enter.native="huiche(field.nextInputId)" :name="field.id"
                    v-model="formInline[field.col_name]"
                    :placeholder="field.msg"></el-input>

          <template v-if="field.col_style == 9">
            <el-radio :disabled="field.is_disabled" :style="'width:'+field.input_width"
                      v-model="formInline[field.col_name]" :label="option.key"
                      v-for="option in field.options">{{option.value}}</el-radio>
          </template>

          <el-switch v-if="field.col_style == 10" :disabled="field.is_disabled" active-value="true"
                     inactive-value="false" v-model="formInline[field.col_name]">
          </el-switch>

          <el-cascader v-if="field.col_style == 11" :ref="field.col_name" clearable filterable
                       :style="'width:'+field.input_width" v-model="formInline[field.col_name]"
                       :props="cascaderProps[field.col_name]"></el-cascader>

          <!--输入列表组件-->
          <template v-if="field.col_style == 14">
            <iframe :name="field.col_name"  fr="gridList"
                    :src="field.list_url+'&tableHeight='+field.tableHeight+'&tableId='+field.data_zygl_id+'&group_id='+field.group_id+'&col_name='+field.col_name"
                    frameborder="0"
                    :style="'width:'+gridListWidth+'px;height:'+(parseInt(field.tableHeight)+50)+'px'"></iframe>
          </template>


          <!--树形选择框-->
          <template v-if="field.col_style == 23">
            <el-input :name="field.id" style="display: none;" :disabled="true"
                      v-model="formInline[field.col_name]" :placeholder="field.msg"
                      :style="'width:'+field.input_width"></el-input>
            <el-input :disabled="true" v-model="formInlineShow[field.col_name]"
                      :placeholder="field.msg" :style="'width:'+field.input_width"></el-input>
            <el-button @click="open_el_tree(field)">选择</el-button>
          </template>

        </el-form-item>

        <div v-if="field.is_inline == '1'" style="display: block;"></div>

      </template>

    </template>


  </el-form>

</template>

<script>
module.exports = {
  name: "inputCommon",
  props: ["tableid","id","mapod","inline"],
  data(){
    return {
      formInline: {},
      formInlineShow: {},
      gridListWidth: $(document.body).width() - 30,
      listcolumns:[],
      rules:{},
      changeColumn:"",
      huicheInput:"",
      cascaderProps: {}, //三级联动动态加载
      headers: {
        token: localStorage.getItem("token")
      },
      uploadListShow: {},

      dialogImageUrl: '',
      dialogVisible: false,

      oldValue:{},
      newValue:{},
    };
  },
  created() {
    this.getColumns();
  },
  methods:{
    alertColumnMsg(){
      for (let key in this.formInline) {
        try {
          let value = this.formInline[key];
          if (this.rules[key] != undefined && value == "") {
            console.log("key",key)
            top.error("红*号必输项不能为空!" + key);
            return false;
          }
        } catch (e) {}
      }
      return true;
    },
    async verification(){
      //验证录入页面是否填写完整
      try {
        await this.$refs["ruleForm"].clearValidate();
        await this.$refs["ruleForm"].validate();
        let v = this.alertColumnMsg();
        return v;
      } catch (e) {
        this.alertColumnMsg();
        return false;
      }
    },
    async getInputData(){
      let v = await this.verification();
      if(v){
        return this.formInline;
      }
      return v;

    },

    fileListTransi(src, field) {
      if (src == null || src == undefined || src == "") {
        return;
      }
      let urls = src.split(",");
      let fileList = [];
      for (let a = 0; a < urls.length; a++) {
        fileList.push({
          name: "",
          url: urls[a]
        });
      }
      Vue.set(this.uploadListShow, field, fileList);
    },

    //远程搜索下拉框
    async remoteMethod(query, index, itemList) {
      let field = itemList[index];
      const res = await postBody(
          "/admin/api/DataManagementController/DropdownBoxRemoteSearchEvent2", {
            fieldId: field.col_id,
            key: query
          });
      if (res.code == 0) {
        top.alert(res);
        return;
      }
      Vue.set(field, "options", res.data)

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList, field, zygl_id) {
      let urls = "";
      for (let a = 0; a < fileList.length; a++) {
        let url = fileList[a].url;
        if (url.indexOf("blob:") == -1) {
          if (urls == "") {
            urls = url;
          } else {
            urls = urls + "," + url;
          }
        }

      }
      this.formInline[field] = urls;
    },
    uploadSuccess(response, file, fileList) {
      let field = response.data.field;
      if (this.formInline[field] == undefined || this.formInline[field] == "") {
        this.formInline[field] = response.data.src;
      } else {
        this.formInline[field] = this.formInline[field] + "," + response.data.src;
      }
    },
    //打开树形选择框
    open_el_tree(field) {
      if (field.data_zygl_id == "") {
        top.alert("未定义选择数据表");
        return;
      }
      let btn = {
        btn: ['确定', '取消'],
        yes: async function(index, layero) {
          //按钮【按钮一】的回调
          let win = getTopIframe(layero);
          let dataNode = win.getData();
          this.formInline[field.col_name] = dataNode.id;
          this.formInlineShow[field.col_name] = dataNode.title;
          top.close(index);
        },
        btn2: function(index, layero) {
          //按钮【按钮二】的回调
          //return false 开启该代码可禁止点击该按钮关闭
        }
      };

      top.f_layer_open_get("/admin/html/inputCustom/treeSelect.html?tableId=" + field.data_zygl_id,
          "40%", "80%",
          function() {

          }, btn, field.show_name + "-选择", this.formInline);
    },
    setMapdata(){
      let columnlist = this.listcolumns;
      let cols = [];
      for (let i = 0; i < columnlist.length; i++) {
        let columnList = columnlist[i].columns;
        for(let a=0;a<columnList.length;a++){
          cols.push(columnList[a]);
        }
      }

      for (let i = 0; i < cols.length; i++) {
        if (cols[i].col_style == "4") {
          let src = this.formInline[cols[i].col_name];
          this.fileListTransi(src, cols[i].col_name);
        }
      }
    },
    async getColumns() {
      const res = await postBody("/admin/api/DataManagementController/ObtainInputFieldsEvent2",{tableId:this.tableid,id:this.id});
      if(res.code == 0){
        top.alert(res);
        return;
      }
      this.listcolumns = res.data.columns;
      this.rules = res.data.rules;
      this.formInline = res.data.mapod;
      if(this.id == "" && this.mapod != ""){
        this.formInline = this.mapod;
      }
      this.setMapdata();
    },
    changeFormSubmit(v) {
      this.changeColumn = v;
    },
    //输入框回车事件
    huiche(field) {
      if (field != undefined) {
        let refid = field.nextInputId;
        if (refid != undefined) {
          this.huicheInput = field;
          $("[name='" + refid + "']")[0].focus();
        }
      }
    },

    changePost: throttle(async function() {
      const res = await postBody(
          "/admin/api/DataManagementController/inputBoxChangeEvent", {
            tableId: this.tableId,
            mapdata: {
              "oldValue": this.oldValue,
              "newValue": this.newValue
            },
            other: {
              fieldList: this.listcolumns,
              rules: this.rules,
              changeColumn: this.changeColumn
            }
          });
      if (res.code == 1) {
        this.listcolumns = res.data.other.fieldList;
        this.formInline = res.data.mapdata.newValue;
        this.rules = res.data.other.rules;
        this.changeColumn = "";

        //循环列表重新加载数据
        let listcol = this.listcolumns;
        for (let i = 0; i < listcol.length; i++) {
          if (listcol[i].col_style == "14") {
            let src = $("[name=" + listcol[i].col_name + "]").attr("src");
            $("[name=" + listcol[i].col_name + "]").attr("src", src);
          }
        }
      } else if ("未定义录入事件接口" != res.msg) {
        top.error(res.msg);
      }
    }, 800)
  },
  computed: {
    formInlineFun() {
      return JSON.parse(JSON.stringify(this.formInline));
    },
  },
  watch: {
    formInlineFun: {
      async handler(newValue, oldValue) {
        let isdif = diff(newValue, oldValue);
        if (isdif) {
          return;
        }
        if (Object.keys(oldValue).length == 0) {
          return;
        }
        this.oldValue = oldValue;
        this.newValue = newValue;
        this.changePost();
        return;
      },
      deep: true
    }
  }
}
</script>

<style>
.changeLHight .el-form-item__label {
  line-height: 15px !important;
}

.el-collapse-item__content {
  padding-bottom: 0px;
}

.el-upload-dragger {
  width: 348px;
}

.demo-form-inline {
  margin-bottom: 20px;
}


.title {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.title span {
  font-size: 14px;
  padding-bottom: 10px;
  border-bottom: 2px solid #000;
}
</style>